# models/workflow.py
from datetime import datetime
from uuid import uuid4
from utils.database import db


class WorkflowTemplate(db.Model):
    """流程模板表"""
    __tablename__ = 'workflow_templates'

    id = db.Column(db.Integer, primary_key=True, comment='主键ID，自动递增')
    name = db.Column(
        db.String(100),
        nullable=False,
        unique=True,
        comment='模板名称（需唯一），示例：费用报销审批流程'
    )
    description = db.Column(
        db.Text,
        comment='流程模板详细说明，最长500字符'
    )
    created_at = db.Column(
        db.DateTime,
        default=datetime.utcnow,
        comment='模板创建时间，UTC时区'
    )
    steps = db.relationship('WorkflowStep', backref='template', lazy='dynamic')  # 一对多关系，一个模板对应多个步骤


class WorkflowStep(db.Model):
    """流程步骤配置表"""
    __tablename__ = 'workflow_steps'

    id = db.Column(db.Integer, primary_key=True, comment='步骤ID，自动递增')
    template_id = db.Column(
        db.Integer,
        db.ForeignKey('workflow_templates.id', ondelete='CASCADE'),
        comment='关联流程模板ID',
        nullable=False
    )
    step_order = db.Column(
        db.Integer,
        comment='步骤顺序编号（从1开始），同一模板内需唯一'
    )
    step_type = db.Column(
        db.Enum('SERIAL', 'PARALLEL'),
        default='SERIAL',
        comment='审批类型：SERIAL-串行审批，PARALLEL-并行审批'
    )
    approve_mode = db.Column(
        db.Enum('ANY', 'ALL'),
        default='ANY',
        comment='审批通过条件：ANY-任意人通过即生效，ALL-需全部审批人通过'
    )
    # 改为直接指定审批人ID列表
    approver_ids = db.Column(
        db.JSON, 
        comment='JSON数组，存储审批人用户ID，示例：[1001, 1002]'
    )
    
    # 改为指定抄送人ID列表
    cc_user_ids = db.Column(
        db.JSON,
        comment='JSON数组，存储抄送人用户ID，示例：[2001, 2002]'
    )
    conditions = db.Column(
        db.JSON,
        comment='条件审批配置，存储JSON格式的条件表达式（预留字段）'
    )


class WorkflowInstance(db.Model):
    """流程实例表"""
    __tablename__ = 'workflow_instances'

    id = db.Column(
        db.String(36),
        primary_key=True,
        default=lambda: str(uuid4()),
        comment='流程实例UUID，全局唯一标识'
    )
    template_id = db.Column(
        db.Integer,
        db.ForeignKey('workflow_templates.id'),
        comment='关联的流程模板ID',
        nullable=False
    )
    current_step = db.Column(
        db.Integer,
        default=1,
        comment='当前所处审批步骤编号（对应workflow_steps.step_order）'
    )
    status = db.Column(
        db.Enum('PENDING', 'APPROVED', 'REJECTED'),
        default='PENDING',
        comment='流程状态：PENDING-审批中，APPROVED-已通过，REJECTED-已驳回'
    )
    form_data = db.Column(
        db.JSON,
        comment='JSON格式的表单提交数据，存储所有业务字段'
    )
    initiator_id = db.Column(
        db.Integer,
        comment='流程发起人ID，关联用户表',
        nullable=False
    )
    created_at = db.Column(
        db.DateTime,
        default=datetime.utcnow,
        comment='流程创建时间，UTC时区'
    )
    updated_at = db.Column(
        db.DateTime,
        onupdate=datetime.utcnow,
        comment='最后更新时间，UTC时区'
    )


class ApprovalRecord(db.Model):
    """审批记录表"""
    __tablename__ = 'approval_records'

    id = db.Column(db.Integer, primary_key=True, comment='审批记录ID，自动递增')
    instance_id = db.Column(
        db.String(36),
        db.ForeignKey('workflow_instances.id', ondelete='CASCADE'),
        comment='关联的流程实例ID',
        nullable=False
    )
    step_order = db.Column(
        db.Integer,
        comment='审批步骤编号（对应workflow_steps.step_order）',
        nullable=False
    )
    approver_id = db.Column(
        db.Integer,
        comment='审批人用户ID，关联用户表',
        nullable=False
    )
    decision = db.Column(
        db.Enum('APPROVE', 'REJECT'),
        comment='审批决定：APPROVE-通过，REJECT-驳回'
    )
    comment = db.Column(
        db.Text,
        comment='审批意见，最长500字符'
    )
    decision_time = db.Column(
        db.DateTime,
        default=datetime.utcnow,
        comment='审批操作时间，UTC时区'
    )


class CCRecord(db.Model):
    """抄送记录表"""
    __tablename__ = 'cc_records'

    id = db.Column(db.Integer, primary_key=True, comment='抄送记录ID，自动递增')
    instance_id = db.Column(
        db.String(36),
        db.ForeignKey('workflow_instances.id', ondelete='CASCADE'),
        comment='关联的流程实例ID',
        nullable=False
    )
    user_id = db.Column(
        db.Integer,
        comment='被抄送人用户ID，关联用户表',
        nullable=False
    )
    viewed = db.Column(
        db.Boolean,
        default=False,
        comment='是否已查看：True-已读，False-未读'
    )
    cc_time = db.Column(
        db.DateTime,
        default=datetime.utcnow,
        comment='抄送时间，UTC时区'
    )
